<template>
  <div class="container">
    <el-form
      :model="ruleForm"
      :rules="rules"
      ref="ruleForm"
      label-width="100px"
      class="demo-ruleForm"
    >
      <el-form-item label="商品名称" prop="name">
        <el-input v-model="ruleForm.name"></el-input>
      </el-form-item>
      <el-form-item label="商品价格" prop="price">
        <el-input v-model="ruleForm.price"></el-input>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="submitForm('ruleForm')">保存</el-button>
        <el-button @click="resetForm('ruleForm')">重置</el-button>
      </el-form-item>
    </el-form>
  </div>
</template>

<script>
// import { getDataById, updateData } from '../../api/products'

export default {
  data() {
    return {
      // 表单中的数据
      ruleForm: {
        name: '',
        price: 0
      },
      // 验证规则
      rules: {
        name: [
          { required: true, message: '请输入商品名称', trigger: 'blur' }
          // {
          //   min: 3,
          //   max: 5,
          //   message: '长度在 3 到 5 个字符',
          //   trigger: 'blur',
          // },
        ],
        price: [{ required: true, message: '请输入商品价格', trigger: 'blur' }]
      }
    }
  },
  // 组件创建完成
  created() {
    // 根据id获取当前的数据
    // getDataById(this.$route.query.id).then((res) => {
    //   console.log(res)
    //   this.ruleForm = { name: res.name, price: res.price }
    // })
  },
  methods: {
    submitForm(formName) {
      // $refs属性可以获取当前的dom元素
      //  调用表单的验证方法validate
      //  如果成功返回一个true
      this.$refs[formName].validate((valid) => {
        // eslint-disable-line
        if (valid) {
          // alert('submit!');
          // 此处做数据提交
          // updateData(this.$route.query.id, this.ruleForm).then(() => {
          //   this.$router.push({
          //     name: 'ProductList'
          //   })
          // })
        } else {
          console.log('error submit!!')
          return false
        }
      })
    },
    resetForm(formName) {
      this.$refs[formName].resetFields()
    }
  }
}
</script>

<style></style>
